package com.ubing.boot.notesforjava.test.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @ClassName : sokect_NIO3_netty
 * @Description : sokect_NIO3_netty
 * @Author : Xxxxx
 * @Date: 2023-03-25 21:38
 */
public class sokect_NIO3_netty {

    public static void main(String[] args) {
        try {
            nettyBegin(new soket_NIO3_netty_handler_impl());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void nettyBegin(soket_NIO3_netty_handler soketNio3NettyHandler) throws IOException {
        //创建NIO
        ServerSocketChannel serverSocket=ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9302));
        // 设置socket为非阻塞
        serverSocket.configureBlocking(false);
        // 打开Selector 处理channel，即创建epoll
        Selector selector = Selector.open();//  Selector 多路复用器   =》  Selector会监听serverSocket端口是否发送io事件
        // 把ServerSocketChannel注册到selector上，并且设置selector对客户端accept连接操作感兴趣
        serverSocket.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务启动成功");
        while(true){
            // 阻塞等待需要处理的事件  // 会让出cpu
            selector.select();

            // 获取selector中注册的全部事件的SelcetionKey 实例
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            // 遍历SelcetionKey对事件进行处理
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                // 如果是OP_ACCEPT事件，则进行链接获取和事件注册
                if(key.isAcceptable()){
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel accept = server.accept();
                    accept.configureBlocking(false);
                    // 这里注册读事件，如果需要客服端发送数据，可以注册写事件
                    accept.register(selector,SelectionKey.OP_READ);
                    soketNio3NettyHandler.linkHandler();
                }else if(key.isReadable()){
                    SocketChannel channel = (SocketChannel)key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int len = channel.read(byteBuffer);
                    if(len>0){
                        soketNio3NettyHandler.readHandler(new String(byteBuffer.array()));
                    } else if(len==-1){
                        System.out.println("客户端断开链接");
                        channel.close();
                    }
                }
                // 从事件集合里删除本次处理的key，防止下次select重复处理
                iterator.remove();
            }

        }
    }
}
